<template>
  <div class="pane-account">
    <el-form
      :rules="accountRules"
      :model="account"
      label-width="60px"
      size="large"
      ref="formRef"
    >
      <el-form-item label="帐号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules, ElForm } from 'element-plus'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { loaclCache } from '@/utils/cache'
const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'
// 定义account数据
const account = reactive<IAccount>({
  name: loaclCache.getCache(CACHE_NAME) || '', // coderwhy
  password: loaclCache.getCache(CACHE_PASSWORD) || '' // 123456
})
// 定义校验规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '帐号不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,20}$/,
      message: '帐号长度为6-20位的数字或字母组成',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{3,}$/,
      message: '密码必须为3位以上的数字或字母组成',
      trigger: 'blur'
    }
  ]
}
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
// 执行登录逻辑
const loginAction = (isRemPwd: Boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      // 请求数据
      loginStore.loginAccountAction({ name, password }).then(() => {
        // 判断是否需要记录密码
        if (isRemPwd) {
          loaclCache.setCache(CACHE_NAME, name)
          loaclCache.setCache(CACHE_PASSWORD, password)
        } else {
          loaclCache.delectCache(CACHE_NAME)
          loaclCache.delectCache(CACHE_PASSWORD)
        }
      })
    } else {
      ElMessage.error('请输入正确格式在操作')
    }
  })
}
// 暴露当前组件的数据
defineExpose({
  loginAction,
  account
})
</script>

<style lang="less" scoped>
// .pane-account {
// }
</style>
../../../types
